package com.base.cn.platform.os.controller.mobile.order.goods;

import com.base.cn.platform.os.common.MobileBaseController;
import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.order.OrderSource;
import com.base.cn.platform.os.common.utils.order.OrderStatus;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.DeviceUtils;
import com.base.cn.platform.os.entity.op.ActivityCodeCondition;
import com.base.cn.platform.os.entity.order.order.OrderCondition;
import com.base.cn.platform.os.entity.order.order.OrderType;
import com.base.cn.platform.os.service.manage.config.SysConfigService;
import com.base.cn.platform.os.service.manage.op.activity.OpActivityService;
import com.base.cn.platform.os.service.manage.op.coupon.OpCouponCodeService;
import com.base.cn.platform.os.service.manage.order.goods.OrderService;
import com.base.cn.platform.os.service.manage.user.account.CusUserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 订单Controller
 *
 * @author s.li
 * @create 2018-06-25-14:06
 */
@Controller
@RequestMapping("/mobile/uc/order")
public class MobileOrderController extends MobileBaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private CusUserAccountService cusUserAccountService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private OpActivityService opActivityService;
    @Autowired
    private OpCouponCodeService opCouponCodeService;

    /**
     * 创建订单
     * @return
     */
    @RequestMapping("/createPayOrder")
    @ResponseBody
    public Map<String,Object> createPayOrder(HttpServletRequest request,
                                             @RequestBody Map<String,Object> orderDataFrom){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        orderDataFrom.put("userId",userId);
        orderDataFrom.put("orderForm", OrderSource.ORDER_FORM_MOBILE);
        //创建订单
        Map<String,Object> resultMap = orderService.createPayOrder(orderDataFrom);
        if(ResultUtil.getSuccess(resultMap)){
            //得到订单对象
            Map<String,Object> order = (Map<String,Object>)ResultUtil.getEntity(resultMap);
            String orderStatus = (String)order.get("orderStatus");
            String url;
            if(orderStatus.equals(OrderStatus.SUCCESS)){//如果订单已经支付成功
                url = "/mobile/pay/payMessage?orderNo="+order.get("orderNo")+"&type=2";
            }else {//如果订单未支付成功
                String payType = (String)orderDataFrom.get("payType");
                String orderType = (String)orderDataFrom.get("orderType");
                url = "/mobile/uc/pay/gotoPay?payType="+payType+"&orderNo="+order.get("orderNo")+"&orderType="+orderType;
                if(orderType.equals(OrderType.ACCOUNT.getKey())){
                    double sumPrice = Double.parseDouble(order.get("sumPrice").toString());
                    url+="&price="+Math.abs(sumPrice);
                }
            }
            resultMap.put("url",url);
        }
        return resultMap;
    }

    /**
     * H5生成免费订单
     * @param request HttpServletRequest
     * @param payType 支付类型，MEMBER,FREE目前只支持两种
     * @param shopData 商品数据包
     * @return Map<String,Object>
     */
    @RequestMapping("/genFreeOrder")
    @ResponseBody
    public Map<String,Object> genFreeOrder(HttpServletRequest request,
                                           @RequestParam("payType") String payType,
                                           @RequestParam("shopData") String shopData){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> orderDataFrom = new HashMap<>();
        orderDataFrom.put("userId",userId);
        orderDataFrom.put("shopData",shopData);
        orderDataFrom.put("payType",payType);
        orderDataFrom.put("orderForm",OrderSource.ORDER_FORM_MOBILE);
        return orderService.createWebFreeOrder(orderDataFrom);
    }

    /**
     * 初始化提交订单页面
     * @param request
     * @param model
     * @param orderType 订单类型
     * @param shopData 商品数据包
     * @return
     */
    @RequestMapping("/initPayOrder")
    public String initPayOrder(HttpServletRequest request,
                                Model model,
                                @RequestParam("orderType") String orderType,
                                @RequestParam(value = "shopData") String shopData){
        model.addAttribute("orderType",orderType);
        model.addAttribute("shopData",shopData);
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        if(orderType.equals(OrderType.COMMON.getKey())){
            Map<String,Object> userAccount = cusUserAccountService.userAccountInfo(userId,false);
            if ("ACTIVE".equalsIgnoreCase(userAccount.get("accountStatus").toString())) {
                model.addAttribute("userAccount",userAccount);
            }
        }
        //获取支付配置
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.PAY);
        model.addAttribute("configMap",configMap);

        boolean isWeiXin = DeviceUtils.isWeChat(request);
        model.addAttribute("isWeiXin",isWeiXin);

        return resultPage("/order/goods/order-init");
    }

    /**
     * 重新支付页面
     * @param id 订单ID
     * @return 操作页面
     */
    @RequestMapping("/newlyOrder")
    public String newlyOrder(HttpServletRequest request,
                             Model model,
                             @RequestParam("id") BigDecimal id){
        OrderCondition condition = new OrderCondition();
        condition.setId(id);
        condition.setSetUserData(false);
        condition.setSetDetailsData(true);
        condition.setSetShopData(true);
        condition.setSetOrderBook(true);
        Map<String,Object> order = orderService.findOrderInfo(condition);
        model.addAttribute("order",order);
        if(OrderType.COMMON.getKey().equals(order.get("orderType").toString())){
            BigDecimal activityId = new BigDecimal(order.get("activityId").toString());
            if(DataUtil.idIsNotNull(activityId)){
                Map<String,Object> activity = opActivityService.queryOpActivityById(activityId,false,false,false,false);
                model.addAttribute("activity",activity);
            }
            BigDecimal couponCodeId = new BigDecimal(order.get("couponCodeId").toString());
            if(DataUtil.idIsNotNull(couponCodeId)){
                Map<String,Object> couponCode = opCouponCodeService.findCouponCodeById(couponCodeId,true);
                model.addAttribute("couponCode",couponCode);
            }
            BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
            Map<String,Object> userAccount = cusUserAccountService.userAccountInfo(userId,false);
            if ("ACTIVE".equalsIgnoreCase(userAccount.get("accountStatus").toString())) {
                model.addAttribute("userAccount",userAccount);
            }
        }
        boolean isWeiXin = DeviceUtils.isWeChat(request);
        model.addAttribute("isWeiXin",isWeiXin);
        //获取支付配置
        TreeMap<String,String> configMap = sysConfigService.getSysConfigContext(ConfigName.PAY);
        model.addAttribute("configMap",configMap);
        return resultPage("/order/goods/newly-order");
    }

    /**
     * 获取商品数据
     * @param shopData 商品包数据
     * @return 商品列表页面
     */
    @RequestMapping("/getPayOrderShopList")
    @ResponseBody
    public Map<String,Object> getPayOrderShopList(HttpServletRequest request,
                                    @RequestParam("orderType") String orderType,
                                    @RequestParam(value = "shopData") String shopData,
                                    @RequestParam(value = "activityId",required = false,defaultValue = "0") BigDecimal activityId,
                                    @RequestParam(value = "couponCode",required = false) String couponCode){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        Map<String,Object> params = new HashMap<>();
        params.put("shopData",shopData);
        params.put("orderType",orderType);
        params.put("activityId",activityId);
        params.put("userId",userId);
        params.put("code",couponCode);
        return orderService.getPayOrderShopList(params);

    }

    /**
     * 获取优惠券和活动
     * @param request
     * @param paramsList 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping("/findOrderAvailableActivityAndCode")
    @ResponseBody
    public Map<String,Object> findOrderAvailableActivityAndCode(HttpServletRequest request,
                                              @RequestParam("filterActivity") boolean filterActivity,
                                              @RequestParam("filterCode") boolean filterCode,
                                              @RequestBody List<Map<String,String>> paramsList){
        BigDecimal userId = webMobileLoginUtil.getLoginUserId(request);
        ActivityCodeCondition condition = new ActivityCodeCondition();
        condition.setUserId(userId);
        condition.setFilterActivity(filterActivity);
        condition.setFilterCode(filterCode);
        condition.setParamsList(paramsList);
        return opActivityService.findOrderAvailableActivityAndCode(condition);
    }
}
